import { hasPermission, hasRole } from '@/utils/auth'
import { BasicLayout, BlankLayout, RouteView, NoMenuLayout } from '@/layouts'
import { getRoutePages } from '@/utils/batchImportFiles'
import Exp404 from '@/pages/exception/404.vue'
// import staticMenus from '@/router/staticMenus'
import i18n from '@/locales/useI18n'
// eslint-disable-next-line @typescript-eslint/ban-types
const constantRouterComponents: { [x: string]: Function } = {
  // 基础页面 layout 必须引入
  BasicLayout,
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  BlankLayout,
  RouteView,
  // PageView,
  ...getRoutePages()
}
const buildMenuTree = (app, menus?: any, userRoles?: Array<any>, userPermissions?: Array<any>) => {
  const newMenu: Array<any> = []
  // newMenu.push(...formatStaticMenus(JSON.parse(JSON.stringify(staticMenus))))
  menus?.forEach((menu) => {
    if (!menu.parentId) {
      const item = buildMenuItem(app, menus, menu, null, userRoles, userPermissions)
      if (item) {
        newMenu.push(item)
      }
    }
  })
  return newMenu
}
const formatStaticMenuItem = (menu?: any, parentMenu?: any) => {
  const path = menu.path.indexOf('/') != 0 ? '/' + menu.path : menu.path
  const children: Array<any> = []
  const item = {
    path: menu.path,
    component: menu.component,
    fullPath: parentMenu ? parentMenu.fullPath + path : path,
    meta: {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      //@ts-ignore
      title: i18n.global.t(menu.meta.title),
      icon: menu.meta.icon,
      keepAlive: menu.meta.keepAlive
    },
    children: children
  }
  if (menu.children && menu.children.length > 0) {
    menu.children.forEach((subMenu) => {
      item.children.push(formatStaticMenuItem(subMenu, menu))
    })
  }
  return item
}
const formatStaticMenus = (menus?: any) => {
  const newMenu: Array<any> = []

  menus?.forEach((menu) => {
    if (!menu.parentId) {
      const item = formatStaticMenuItem(menu, null)
      newMenu.push(item)
    }
  })
  return newMenu
}
const buildMenuChildren = (
  app,
  menus?: Array<any>,
  menu?: any,
  parentId?: string,
  userRoles?: Array<any>,
  userPermissions?: Array<any>
) => {
  menus?.forEach((subMenu) => {
    if (subMenu.parentId == parentId) {
      const item = buildMenuItem(app, menus, subMenu, menu, userRoles, userPermissions)
      if (item) {
        menu.children.push(item)
      }
    }
  })
}
const buildMenuItem = (
  app,
  menus?: Array<any>,
  menu?: any,
  rootMenu?: any,
  userRoles?: Array<any>,
  userPermissions?: Array<any>
) => {
  const roles: Array<any> = []
  const permissions: Array<any> = []
  if (menu.roleList) {
    menu.roleList.forEach(({ name }) => {
      roles.push(name)
    })
  }
  if (menu.permissionList) {
    menu.permissionList.forEach(({ name }) => {
      permissions.push(name)
    })
  }
  if (permissions.length > 0 && !hasPermission(permissions, userPermissions)) {
    return null
  }
  if (roles.length > 0 && !hasRole(roles, userRoles)) {
    return null
  }
  const _parentPath: Array<any> = []
  let path = menu.path
  let component = menu.component
  const query = {}
  if (path.indexOf('?') != -1) {
    const args = path.substr(path.indexOf('?') + 1)
    path = path.substr(0, path.indexOf('?'))
    args.split('&').forEach((a) => {
      const key = a.split('=')[0]
      const value = a.split('=')[1]
      query[key] = value
    })
  }
  if (component && component.indexOf('?') != -1) {
    const args = component.substr(component.indexOf('?') + 1)
    component = component.substr(0, component.indexOf('?'))
    args.split('&').forEach((a) => {
      const key = a.split('=')[0]
      const value = a.split('=')[1]
      query[key] = value
    })
  }
  const path2 = path.indexOf('/') != 0 ? '/' + path : path
  const item = {
    key: menu.id,
    children: [],
    path: path,
    fullPath: rootMenu ? rootMenu.fullPath + path2 : '/' + app + path2,
    component: component,
    _parentPath: _parentPath,
    meta: {
      icon: menu.icon,
      title: menu.title,
      query: query
    }
  }
  if (rootMenu) {
    if (rootMenu._parentPath && rootMenu._parentPath.length > 0) {
      item._parentPath.push(...rootMenu._parentPath)
    }
    item._parentPath.push(rootMenu.fullPath)
  }
  buildMenuChildren(app, menus, item, menu.id, userRoles, userPermissions)
  if (item.children.length == 0 && !item.component) {
    return null
  }
  // if(item.children.length>0){
  //   item.redirect = findFirstMenu(item.fullPath, item.children)
  // }
  return item
}
const buildRouterTree = (menus?: any, app: string) => {
  const newMenu: Array<any> = []
  menus.forEach((menu) => {
    const item = buildRouterItem(menu)
    newMenu.push(item)
  })
  console.log(newMenu)
  if (newMenu.length == 1 && ((!newMenu[0].children) || (newMenu[0].children.length == 0))) {
    return [
      {
        path: '/' + app,
        name: app,
        component: NoMenuLayout,
        meta: {},
        redirect: findFirstMenu('/' + app, newMenu),
        children: newMenu
      }
    ]
  }
  return [
    {
      path: '/' + app,
      name: app,
      component: BasicLayout,
      meta: {},
      redirect: findFirstMenu('/' + app, newMenu),
      children: newMenu
    }
  ]
}
const findFirstMenu: string = (parentPath: string, menus?: any) => {
  if (menus && menus.length > 0) {
    const menu = menus[0]
    if (menu.children && menu.children.length > 0) {
      return findFirstMenu(parentPath + '/' + menu.path, menu.children)
    }
    return parentPath + '/' + menu.path
  }
  return null
}
const buildRouterItem: any = (menu?: any) => {
  const component = menu.component
    ? constantRouterComponents[menu.component]
      ? constantRouterComponents[menu.component]
      : Exp404
    : RouteView
  if (component == Exp404) {
    console.error(menu.path + '不存在!')
  }
  const children: Array<any> = []
  let path = menu.path
  const query = {}
  if (path.indexOf('?') != -1) {
    const args = path.substr(path.indexOf('?') + 1)
    path = path.substr(0, path.indexOf('?'))
    args.split('&').forEach((a) => {
      const key = a.split('=')[0]
      const value = a.split('=')[1]
      query[key] = value
    })
  }
  const item = {
    children: children,
    component: component,
    meta: {
      icon: menu.meta.icon,
      title: menu.meta.title,
      query: query
    },
    path: path
  }

  if (menu.children && menu.children.length > 0) {
    menu.children.forEach((subMenu) => {
      item.children.push(buildRouterItem(subMenu))
    })
  }
  return item
}
const findMenuByPath: any = (menu?: any, fullPath?: any) => {
  let res = null
  if (menu && menu.length > 0) {
    menu.forEach((item) => {
      if (item.fullPath == fullPath) {
        res = item
      } else {
        if (!res) {
          res = findMenuByPath(item.children, fullPath)
        }
      }
    })
  }
  return res
}
export { buildRouterTree, buildMenuTree, findMenuByPath }
